package br.com.ravi.deposito.utils.hibernate;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import br.com.ravi.deposito.vo.CustomerVO;
import br.com.ravi.deposito.vo.UserVO;

/**
 * 
 * @author Rafael Ingaramo
 *
 */
public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private static Session session;
	@PostConstruct
	public static void buildSessionFactory() {
		try {
			//TODO: Logar
			Configuration configuration = new Configuration();
			configuration.addAnnotatedClass(UserVO.class);
			configuration.addAnnotatedClass(CustomerVO.class);
			
			configuration.configure();
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
					.applySettings(configuration.getProperties())
					.buildServiceRegistry();
			
			SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
			
			HibernateUtil.sessionFactory = sessionFactory;
		} catch (Throwable ex) {
			//TODO: Logar
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

    public static Session getCurrentSession() {
    	if (session == null) {
    		session = sessionFactory.getCurrentSession();
    		if (session == null) {
    			session = sessionFactory.openSession();
    		}
    	}
    	if (!session.isOpen()) {
    		session = sessionFactory.openSession();
    	}
    	
    	return session;
    }
    @PreDestroy
	public static void destroySessionFactory() {
		Session session = getCurrentSession();
		if (session != null) {
			Transaction tx = session.getTransaction();
			
			if (tx != null) {
				tx.rollback();
				tx = null;
			}
			
			session.close();
			session.flush();
			session = null;
		}
		
		if (sessionFactory != null) {
			sessionFactory.close();
			sessionFactory = null;
		}
	}

	public static void closeCurrentSession(boolean exceptionOcurred) {
		Session session = getCurrentSession();
		if (session != null) {
			if (!exceptionOcurred) {
				session.flush();
			}
			session.close();
		}
		
	}
}